import os

from bean.Constants import Constants
from bean.TableInfo import TableInfo

from builder.CommentBuilder import CommentBuilder
from utils.StringUtils import uppercase_first_char


class MapperBuilder:

    @staticmethod
    def execute_build(table_info: TableInfo) -> None:
        if not os.path.exists(Constants.get_instance().MAPPERS_PATH):
            os.makedirs(Constants.get_instance().MAPPERS_PATH)

        with open(
                Constants.get_instance().MAPPERS_PATH + f"{table_info.bean_name}{Constants.get_instance().SUFFIX_MAPPERS}.java",
                "w", encoding="utf-8") as f:
            """
            导包和定义包名
            """
            f.write(f"package {Constants.get_instance().PACKAGE_MAPPERS};\n")
            f.write("\n")
            f.write("import org.apache.ibatis.annotations.Param;\n")
            if table_info.have_date or table_info.have_date_time:
                f.write("\nimport java.util.Date;\n")
            if table_info.have_big_decimal:
                f.write("import java.math.BigDecimal;\n")
            CommentBuilder.build_class_comment(f, table_info.comment, True)
            f.write("\n")

            """
            开始定义Mapper
            """
            f.write(
                f"public interface {table_info.bean_name}{Constants.get_instance().SUFFIX_MAPPERS}<T, P> extends BaseMapper{{\n"
            )
            for i in table_info.field_map.values():
                method_name = uppercase_first_char(i.property_name)
                f.write("\n")
                CommentBuilder.build_filed_comment(f, f"根据{method_name}查询", "\t")
                f.write("\n")
                param = f"@Param(\"{i.property_name}\") {i.java_type} {i.property_name}"
                f.write(f"\tT selectBy{method_name}({param});")
                f.write("\n\n")
                param = f"@Param(\"bean\") T t,  {i.java_type} {i.property_name}"
                CommentBuilder.build_filed_comment(f, f"根据{method_name}更新", "\t")
                f.write("\n")
                f.write(f"\tInteger updateBy{method_name}({param});")
                f.write("\n\n")
                CommentBuilder.build_filed_comment(f, f"根据{method_name}删除", "\t")
                f.write("\n")
                param = f"@Param(\"bean\") T t,  {i.java_type} {i.property_name}"
                f.write(f"\tInteger deleteBy{method_name}({param});")
                f.write("\n")

            f.write("\n}")

